package com.evolve.autotest.actions;

import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

import com.evolve.autotest.ReturnValue;


public class CommandAction extends Action {

	private final static Logger logger = Logger.getLogger(CommandAction.class);
	
	private final String command;
	private final String name;

	/**
	 * Constructor
	 * @param command
	 */
	public CommandAction(final String command) {
		this.command = command;
		name = "command";
	}
	
	/**
	 * Gets the name of the action. In this case "command" will
	 * be returned
	 */
	public String getName() {
		return name;
	}
	
	public ReturnValue execute() {
		
		if (command == null || command.length() == 0) {
			addTrouble("Command does not exist");
			return ReturnValue.ERROR;
		}
		
		try {
			Process process = Runtime.getRuntime().exec(command);
			
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				String message = "Unable to wait for command to finished executing " + command;
				logger.error(message);
				addTrouble(message);
			}
			
			String processOutput = readOutput(process);
			
			int exitValue = process.exitValue();
			
			if (exitValue != 0) {
				addTrouble("Command " + command + " was unable to execute");
				addTrouble(processOutput);
				return ReturnValue.FAILED;
			} 
		} catch (IOException e) {
			addTrouble("Command " + command + " was unable to execute");
			return ReturnValue.ERROR;
		}
		
		return ReturnValue.OK;
	}

	private String readOutput(Process process) {
		InputStream in = process.getInputStream();
		
        int c;
        
        StringBuffer buffer = new StringBuffer();
        
        try {
			while ((c = in.read()) != -1) {
			    buffer.append((char)c);
			}
		} catch (IOException e) {
			return "";
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				return "";
			}
		}
		
		return buffer.toString();
	}
}
